#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import re

PATH='/usr/share/kylin-update-desktop/'

class main:

    def generate_old_system_packagelist(self):
        os.system('dpkg -l > '+ PATH +'dpkgl')
        ff = open(PATH +'old-system-packagelist','w')
        with open(PATH +'dpkgl') as f:
            for line in f:
                if line.startswith('ii  '):
                    line = line.replace('ii  ','')
                    line = re.sub('(  *)arm64(.*)','',line)
                    line = re.sub('(  *)i386(.*)','',line)
                    line = re.sub('(  *)amd64(.*)','',line)
                    line = re.sub('(  *)i686(.*)','',line)
                    line = re.sub('(  *)all(.*)','',line)
                    line = re.sub('(  *)','\t',line)
                    ff.write(line)
        ff.close()

        
    def specification_old_system_packagelist(self):
        f = open(PATH +'old-system-packagelist', mode='r')
        ff = open(PATH + "pkglist", mode='w')
        for line in f:
            linesp = line.split("\t")
            pkgname = linesp[0]
            pkgversion = linesp[1]
            if(pkgname.find(":arm64") != -1):
                pkgname = pkgname[:pkgname.find(":arm64")]
            newline = pkgname + "_" + pkgversion
            ff.write(newline)
        f.close()
        ff.close()

    def generate_install_list(self):
        newnames = []
        oldnames = []
        f = open(PATH +'new-system-packagelist', mode='r')
        ff = open(PATH +'pkglist', mode='r')
        fff = open(PATH +'install', mode='w')
        for line in f:
            newnames.append(line.strip())
        for line in ff:
            oldnames.append(line.strip())
        for name in newnames:
            for nameold in oldnames:
                if(name == nameold):
                    break
            else:
#                name = name.replace('_', '=')
                fff.write(name + '*deb ')
        f.close()
        ff.close()
        fff.close()


if __name__ == '__main__':
    m = main()
    m.generate_old_system_packagelist()
    m.specification_old_system_packagelist()
    m.generate_install_list()

